/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* cur = head;
        int count = 0;
        while (cur)
        {
            count++;
            cur = cur->next;
        }
        n = count - n;

        cur = head;
        ListNode* prev = nullptr;
        if (n == 0)
        {
            return head->next;
        }
        while (n--)
        {
            prev = cur;
            cur = cur->next;
        }
        ListNode* next = cur->next;
        prev->next = next;
        delete cur;
        return head;
    }
};